import { fetchPublicKeyAction } from '@/store/module/app'
import { myShallowEqual, useMyDispatch, useMySelector } from '@/store'
import { useEffect, useState } from 'react'

// 封装一个hook用来获取公钥
function useEncrypt(): [string] {
  const dispatch = useMyDispatch()
  const { storePublicKey } = useMySelector(
    (state) => ({
      storePublicKey: state.app.publicKey
    }),
    myShallowEqual
  )
  const [publicKey, setPublicKey] = useState(storePublicKey)

  useEffect(() => {
    if (!publicKey) {
      dispatch(fetchPublicKeyAction()).then(({ payload }) => {
        setPublicKey(payload)
      })
    }
  }, [publicKey])

  return [publicKey]
}

export default useEncrypt
